package com.gombe.credit.app.ui.fragment

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.graphics.Typeface
import android.text.SpannableString
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.text.style.StyleSpan
import android.view.LayoutInflater
import android.view.View
import androidx.activity.result.ActivityResult
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.PickVisualMediaRequest
import androidx.activity.result.contract.ActivityResultContracts
import com.gombe.credit.app.GombeCreditApp
import com.gombe.credit.app.R
import com.gombe.credit.app.common.CommonFragment
import com.gombe.credit.app.configs.GombeCreditApiPath
import com.gombe.credit.app.configs.GombeCreditApiUrl.addCommonParams
import com.gombe.credit.app.databinding.FragmentGombeCreditStepOcrBinding
import com.gombe.credit.app.event.GombeCreditEventData
import com.gombe.credit.app.event.GombeCreditEventPointType
import com.gombe.credit.app.event.room.GombeCreditPointManager
import com.gombe.credit.app.request.HttpHelper
import com.gombe.credit.app.request.IHttpCallback
import com.gombe.credit.app.ui.activity.ActGombeCreditCameraOcr
import com.gombe.credit.app.ui.activity.ActGombeCreditProcessSteps
import com.gombe.credit.app.ui.dialog.DialogGombeCreditPermissionReason
import com.gombe.credit.app.ui.dialog.DialogGombeCreditPhoto
import com.gombe.credit.app.utils.GombeCreditImageLoader
import com.gombe.credit.app.utils.helper.GombeCreditConfigsHelper
import com.gombe.credit.app.utils.helper.GombeCreditPermissionHelper
import com.gombe.credit.app.utils.imgcovert.ImageConvert
import com.gombe.credit.app.utils.log.GombeCreditLogger
import com.gombe.credit.lib.adapter.GombeCreditOnSingleClickListener
import org.json.JSONObject
import pub.devrel.easypermissions.AppSettingsDialog
import pub.devrel.easypermissions.EasyPermissions

/**
 * GombeCredit
 * @Author wwdeng
 * @CreateTime: 2024/11/21 13:40
 * @Annotation：认证流程 - 身份证、护照、驾驶证
 */
class FragmentGombeCreditStepOcr(): CommonFragment(),EasyPermissions.PermissionCallbacks,EasyPermissions.RationaleCallbacks  {
    private var _binding: FragmentGombeCreditStepOcrBinding? = null
    private val binding get() = _binding ?: throw IllegalStateException(
        "gombe credit step ocr binding because it is null. Either the view hasn't been created yet, or it has already been destroyed."
    )

    private var stepItem: JSONObject? = null
    private var eventRemark = ""

    private val ocrTypeList = arrayListOf<JSONObject>()
    private val typeTitleList = arrayListOf(
        "${R.mipmap.gombe_credit_image_step_ocr_id_card_selected_icon},${GombeCreditApp.app.getString(R.string.gombe_credit_process_step_ocr_type_id_card)},IDCARD",
        "${R.mipmap.gombe_credit_image_step_ocr_passport_selected_icon},${GombeCreditApp.app.getString(R.string.gombe_credit_process_step_ocr_type_passport)},PASSPORT",
        "${R.mipmap.gombe_credit_image_step_ocr_driving_license_selected_icon},${GombeCreditApp.app.getString(R.string.gombe_credit_process_step_ocr_type_driving_license)},DRIVING",
        "${R.mipmap.gombe_credit_image_step_ocr_election_card_selected_icon},${GombeCreditApp.app.getString(R.string.gombe_credit_process_step_ocr_type_election_card)},ELECTIONCARD",
        "${R.mipmap.gombe_credit_image_step_ocr_no_documents_selected_icon},${GombeCreditApp.app.getString(R.string.gombe_credit_process_step_ocr_type_no_documents)},NONE"
    )
    private var selectTypeItem: JSONObject? = null

    private var photoDialog: DialogGombeCreditPhoto? = null

    //是否是正面
    private var isFront = true
    //正面照
    private var imgFrontUrl = ""
    //背面照
    private var imgBackUrl = ""
    //图片选择
    lateinit var pickMedia: ActivityResultLauncher<PickVisualMediaRequest>

    constructor(stepItem: JSONObject): this(){
        this.stepItem = stepItem
        eventRemark = stepItem.optString("stepTitle")
    }

    override fun takeGombeCreditRootView(inflater: LayoutInflater): View {
        _binding = FragmentGombeCreditStepOcrBinding.inflate(inflater)
        return binding.root
    }

    override fun initGombeCreditView() {
        initGombeCreditOcrTypeTitleText()
        initGombeCreditOcrUploadCreditLimitAddTipsText()
        initGombeCreditOcrUploadCreditLimitApprovedTipsText()

        //提交移到外层
        _binding?.buttonOcrNext?.visibility = View.INVISIBLE
    }

    override fun initGombeCreditListener() {
        _binding?.idCardLayout?.setOnClickListener(object : GombeCreditOnSingleClickListener(){
            override fun onSingleClick(v: View?) {
                selectTypeItem = ocrTypeList[0]
                showGombeCreditOcrTypeCheckSelected()
            }
        })

        _binding?.passportLayout?.setOnClickListener(object : GombeCreditOnSingleClickListener(){
            override fun onSingleClick(v: View?) {
                selectTypeItem = ocrTypeList[1]
                showGombeCreditOcrTypeCheckSelected()
            }
        })

        _binding?.drivingLicenseLayout?.setOnClickListener(object : GombeCreditOnSingleClickListener(){
            override fun onSingleClick(v: View?) {
                selectTypeItem = ocrTypeList[2]
                showGombeCreditOcrTypeCheckSelected()
            }
        })

        _binding?.electionCardLayout?.setOnClickListener(object : GombeCreditOnSingleClickListener(){
            override fun onSingleClick(v: View?) {
                selectTypeItem = ocrTypeList[3]
                showGombeCreditOcrTypeCheckSelected()
            }
        })

        _binding?.noDocumentsLayout?.setOnClickListener(object : GombeCreditOnSingleClickListener(){
            override fun onSingleClick(v: View?) {
                selectTypeItem = ocrTypeList[4]
                showGombeCreditOcrTypeCheckSelected()
            }
        })

        //正面
        _binding?.frontLayout?.setOnClickListener(object : GombeCreditOnSingleClickListener(){
            override fun onSingleClick(v: View?) {
                isFront = true
                if (selectTypeItem != null){
                    val eventRemark = "${selectTypeItem?.optString("ocrType")} Front"
                    showGombeCreditOcrPhotoDialog(eventRemark)
                }
            }
        })
        //背面
        _binding?.backLayout?.setOnClickListener(object : GombeCreditOnSingleClickListener(){
            override fun onSingleClick(v: View?) {
                isFront = false
                if (selectTypeItem != null){
                    val eventRemark = "${selectTypeItem?.optString("ocrType")} Back"
                    showGombeCreditOcrPhotoDialog(eventRemark)
                }
            }
        })
        //护照
        _binding?.passportFrontLayout?.setOnClickListener(object : GombeCreditOnSingleClickListener(){
            override fun onSingleClick(v: View?) {
                _binding?.frontLayout?.callOnClick()
            }
        })

        //提交
        _binding?.buttonOcrNext?.setOnClickListener {
            onGombeCreditStepOcrSubmitAction()
        }

        // 1-注册图库组件
        pickMedia = registerForActivityResult(ActivityResultContracts.PickVisualMedia()) { uri ->
            if (uri != null) {
                // 图片处理
                ImageConvert.covert(context = requireContext(), uri = uri) { localPath, bitmap ->
                    if (localPath != null){
                        GombeCreditLogger.e(">>>>>>>album>>>>>>>>>>$localPath")
                        uploadGombeCreditOCRImageAction(localPath)
                    }
                }
            } else {
                GombeCreditLogger.e("No media selected")
            }
        }
    }

    override fun takeGombeCreditData() {
        addEventPointRequestAction(String.format(GombeCreditEventPointType.GOMBECREDIT_TRACK_PAGE.STEP_OCR_XX_START,eventRemark))
        ocrTypeList.clear()
        var ocrTypeSize = typeTitleList.size
        //是否支持选择不传证件照
        if (!GombeCreditConfigsHelper.isShowOcrNoDocuments()){
            ocrTypeSize -= 1
        }
        for (i in 0..< ocrTypeSize){
            val item = JSONObject()
            item.put("iconId",typeTitleList[i].split(",")[0])
            item.put("title",typeTitleList[i].split(",")[1])
            item.put("ocrType",typeTitleList[i].split(",")[2])
            item.put("isSelect",i == 0)
            if (i == 0){
                selectTypeItem = item
            }
            ocrTypeList.add(item)
        }
        //设置显示Ocr类型
        showGombeCreditOcrTypeCheckSelected()
    }

    private fun initGombeCreditOcrTypeTitleText(){
        val showOcrTypeTitle = getString(R.string.gombe_credit_process_step_ocr_select_type)
        val ocrTypeSpannable = SpannableString(showOcrTypeTitle)
        ocrTypeSpannable.setSpan(ForegroundColorSpan(getColor(R.color.gombe_credit_FFFF4D3E)), 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        _binding?.textOcrTypeTitle?.text = ocrTypeSpannable
    }

    private fun initGombeCreditOcrUploadCreditLimitAddTipsText(){
        val creditLimitAmount = stepItem?.optString("creditLimitAmount")
        val showTipsKey1 = String.format(getString(R.string.gombe_credit_process_step_ocr_upload_credit_limit_add_tips_key1),creditLimitAmount)
        val showTipsKey2 = getString(R.string.gombe_credit_process_step_ocr_upload_credit_limit_add_tips_key2)
        val showTipsText = String.format(getString(R.string.gombe_credit_process_step_ocr_upload_credit_limit_add_tips),showTipsKey1,showTipsKey2)
        val startTipsIndex1 = showTipsText.indexOf(showTipsKey1)
        val startTipsIndex2 = showTipsText.indexOf(showTipsKey2)
        val creditLimitTipsSpannable = SpannableString(showTipsText)
        creditLimitTipsSpannable.setSpan(ForegroundColorSpan(getColor(R.color.gombe_credit_ffff2f00)), startTipsIndex1, startTipsIndex1 + showTipsKey1.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        creditLimitTipsSpannable.setSpan(ForegroundColorSpan(getColor(R.color.gombe_credit_ffff2f00)), startTipsIndex2, startTipsIndex2 + showTipsKey2.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        //加粗
        creditLimitTipsSpannable.setSpan(StyleSpan(Typeface.BOLD), startTipsIndex1, startTipsIndex1 + showTipsKey1.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        creditLimitTipsSpannable.setSpan(StyleSpan(Typeface.BOLD), startTipsIndex2, startTipsIndex2 + showTipsKey2.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        _binding?.textOcrUploadCreditLimitAddTips?.text = creditLimitTipsSpannable
    }

    private fun initGombeCreditOcrUploadCreditLimitApprovedTipsText(){
        val showApprovedKey1 = getString(R.string.gombe_credit_process_step_ocr_upload_credit_limit_approved_tips_key1)
        val showApprovedText = String.format(getString(R.string.gombe_credit_process_step_ocr_upload_credit_limit_approved_tips),showApprovedKey1)
        val startApprovedIndex1 = showApprovedText.indexOf(showApprovedKey1)
        val approvedTipsSpannable = SpannableString(showApprovedText)
        approvedTipsSpannable.setSpan(ForegroundColorSpan(getColor(R.color.gombe_credit_FFFF5900)), startApprovedIndex1, startApprovedIndex1 + showApprovedKey1.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        //加粗
        approvedTipsSpannable.setSpan(StyleSpan(Typeface.BOLD), startApprovedIndex1, startApprovedIndex1 + showApprovedKey1.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        _binding?.textOcrUploadCreditLimitApprovedTips?.text = approvedTipsSpannable
    }

    /**
     * 切换选择类型
     */
    private fun onGombeCreditOcrTypeCheckNormal(){
        _binding?.let { binding ->
            binding.idCardLayout.shapeDrawableBuilder
                .setSolidColor(getColor(R.color.gombe_credit_FFF9F9F7))
                .setStrokeColor(getColor(R.color.gombe_credit_FFF9F9F7))
                .intoBackground()
            binding.imageIdCard.setImageResource(R.mipmap.gombe_credit_image_step_ocr_id_card_normal_icon)
            binding.textIdCard.setTextColor(getColor(R.color.gombe_credit_ffa8a8a8))
            binding.imageIdCardSelector.setImageResource(R.mipmap.gombe_credit_image_step_ocr_type_normal_icon)

            binding.passportLayout.shapeDrawableBuilder
                .setSolidColor(getColor(R.color.gombe_credit_FFF9F9F7))
                .setStrokeColor(getColor(R.color.gombe_credit_FFF9F9F7))
                .intoBackground()
            binding.imagePassport.setImageResource(R.mipmap.gombe_credit_image_step_ocr_passport_normal_icon)
            binding.textPassport.setTextColor(getColor(R.color.gombe_credit_ffa8a8a8))
            binding.imagePassportSelector.setImageResource(R.mipmap.gombe_credit_image_step_ocr_type_normal_icon)

            binding.drivingLicenseLayout.shapeDrawableBuilder
                .setSolidColor(getColor(R.color.gombe_credit_FFF9F9F7))
                .setStrokeColor(getColor(R.color.gombe_credit_FFF9F9F7))
                .intoBackground()
            binding.imageDrivingLicense.setImageResource(R.mipmap.gombe_credit_image_step_ocr_driving_license_normal_icon)
            binding.textDrivingLicense.setTextColor(getColor(R.color.gombe_credit_ffa8a8a8))
            binding.imageDrivingLicenseSelector.setImageResource(R.mipmap.gombe_credit_image_step_ocr_type_normal_icon)

            binding.electionCardLayout.shapeDrawableBuilder
                .setSolidColor(getColor(R.color.gombe_credit_FFF9F9F7))
                .setStrokeColor(getColor(R.color.gombe_credit_FFF9F9F7))
                .intoBackground()
            binding.imageElectionCard.setImageResource(R.mipmap.gombe_credit_image_step_ocr_election_card_normal_icon)
            binding.textElectionCard.setTextColor(getColor(R.color.gombe_credit_ffa8a8a8))
            binding.imageElectionCardSelector.setImageResource(R.mipmap.gombe_credit_image_step_ocr_type_normal_icon)

            binding.noDocumentsLayout.shapeDrawableBuilder
                .setSolidColor(getColor(R.color.gombe_credit_FFF9F9F7))
                .setStrokeColor(getColor(R.color.gombe_credit_FFF9F9F7))
                .intoBackground()
            binding.imageNoDocuments.setImageResource(R.mipmap.gombe_credit_image_step_ocr_no_documents_normal_icon)
            binding.textNoDocuments.setTextColor(getColor(R.color.gombe_credit_ffa8a8a8))
            binding.imageNoDocumentsSelector.setImageResource(R.mipmap.gombe_credit_image_step_ocr_type_normal_icon)
        }
    }

    /**
     * 设置选中类型
     */
    private fun showGombeCreditOcrTypeCheckSelected(){
        showGombeCreditOcrTypeViews()
        onGombeCreditOcrTypeCheckNormal()
        _binding?.let { binding ->
            when(selectTypeItem?.optString("ocrType")){
                "IDCARD" -> {
                    binding.idCardLayout.shapeDrawableBuilder
                        .setSolidColor(getColor(R.color.gombe_credit_fffff5b5))
                        .setStrokeColor(getColor(R.color.theme))
                        .intoBackground()
                    binding.imageIdCard.setImageResource(R.mipmap.gombe_credit_image_step_ocr_id_card_selected_icon)
                    binding.textIdCard.setTextColor(getColor(R.color.gombe_credit_ff1d1e20))
                    binding.imageIdCardSelector.setImageResource(R.mipmap.gombe_credit_image_step_ocr_type_selected_icon)
                }
                "PASSPORT" -> {
                    binding.passportLayout.shapeDrawableBuilder
                        .setSolidColor(getColor(R.color.gombe_credit_fffff5b5))
                        .setStrokeColor(getColor(R.color.theme))
                        .intoBackground()
                    binding.imagePassport.setImageResource(R.mipmap.gombe_credit_image_step_ocr_passport_selected_icon)
                    binding.textPassport.setTextColor(getColor(R.color.gombe_credit_ff1d1e20))
                    binding.imagePassportSelector.setImageResource(R.mipmap.gombe_credit_image_step_ocr_type_selected_icon)
                }
                "DRIVING" -> {
                    binding.drivingLicenseLayout.shapeDrawableBuilder
                        .setSolidColor(getColor(R.color.gombe_credit_fffff5b5))
                        .setStrokeColor(getColor(R.color.theme))
                        .intoBackground()
                    binding.imageDrivingLicense.setImageResource(R.mipmap.gombe_credit_image_step_ocr_driving_license_selected_icon)
                    binding.textDrivingLicense.setTextColor(getColor(R.color.gombe_credit_ff1d1e20))
                    binding.imageDrivingLicenseSelector.setImageResource(R.mipmap.gombe_credit_image_step_ocr_type_selected_icon)
                }
                "ELECTIONCARD" -> {
                    binding.electionCardLayout.shapeDrawableBuilder
                        .setSolidColor(getColor(R.color.gombe_credit_fffff5b5))
                        .setStrokeColor(getColor(R.color.theme))
                        .intoBackground()
                    binding.imageElectionCard.setImageResource(R.mipmap.gombe_credit_image_step_ocr_election_card_selected_icon)
                    binding.textElectionCard.setTextColor(getColor(R.color.gombe_credit_ff1d1e20))
                    binding.imageElectionCardSelector.setImageResource(R.mipmap.gombe_credit_image_step_ocr_type_selected_icon)

                }
                else -> {
                    binding.noDocumentsLayout.shapeDrawableBuilder
                        .setSolidColor(getColor(R.color.gombe_credit_fffff5b5))
                        .setStrokeColor(getColor(R.color.theme))
                        .intoBackground()
                    binding.imageNoDocuments.setImageResource(R.mipmap.gombe_credit_image_step_ocr_no_documents_selected_icon)
                    binding.textNoDocuments.setTextColor(getColor(R.color.gombe_credit_ff1d1e20))
                    binding.imageNoDocumentsSelector.setImageResource(R.mipmap.gombe_credit_image_step_ocr_type_selected_icon)
                }
            }
        }
    }

    /**
     * 显示Ocr类型
     */
    private fun showGombeCreditOcrTypeViews(){
        showGombeCreditOcrDataSecurityTextView()
        _binding?.let {  binding ->
            binding.ocrDataSecurityLayout?.visibility = View.VISIBLE
            binding.textShowOcrType.text = selectTypeItem?.optString("title")
            binding.textShowOcrType.visibility = View.VISIBLE

            imgFrontUrl = ""
            imgBackUrl = ""

            //选择上传证件照激励文案，只有选择 “No documents” 才显示
            binding.ocrUploadCreditLimitAddTipsLayout.visibility = View.GONE
            //默认显示正、反面图片
            binding.ocrImageLayout.visibility = View.VISIBLE

            //默认显示正反面View
            binding.frontLayout.visibility = View.VISIBLE
            binding.backLayout.visibility = View.VISIBLE
            binding.passportFrontLayout.visibility = View.GONE

            val ocrType = selectTypeItem?.optString("ocrType")
            when(ocrType){
                "IDCARD" -> {
                    binding.imageFront.setImageResource(R.mipmap.gombe_credit_image_step_ocr_id_card_front_icon)
                    binding.frontMaskLayout.visibility = View.GONE
                    binding.imageBack.setImageResource(R.mipmap.gombe_credit_image_step_ocr_id_card_back_icon)
                    binding.backMaskLayout.visibility = View.GONE
                    binding.textFront.text = getString(R.string.gombe_credit_process_step_ocr_click_upload)
                    binding.textBack.text = getString(R.string.gombe_credit_process_step_ocr_click_upload)
                }
                "PASSPORT" -> {
                    binding.imagePassportFront.setImageResource(R.mipmap.gombe_credit_image_step_ocr_passport_icon)
                    binding.passportMaskLayout.visibility = View.GONE
                    binding.textPassportFront.text = getString(R.string.gombe_credit_process_step_ocr_click_upload)

                    binding.frontLayout.visibility = View.GONE
                    binding.backLayout.visibility = View.GONE
                    binding.passportFrontLayout.visibility = View.VISIBLE
                }
                "DRIVING" -> {
                    binding.imageFront.setImageResource(R.mipmap.gombe_credit_image_step_ocr_driving_license_front_icon)
                    binding.frontMaskLayout.visibility = View.GONE
                    binding.imageBack.setImageResource(R.mipmap.gombe_credit_image_step_ocr_driving_license_back_icon)
                    binding.backMaskLayout.visibility = View.GONE
                    binding.textFront.text = getString(R.string.gombe_credit_process_step_ocr_click_upload)
                    binding.textBack.text = getString(R.string.gombe_credit_process_step_ocr_click_upload)
                }
                "ELECTIONCARD" -> {
                    binding.imageFront.setImageResource(R.mipmap.gombe_credit_image_step_ocr_election_card_front_icon)
                    binding.frontMaskLayout.visibility = View.GONE
                    binding.imageBack.setImageResource(R.mipmap.gombe_credit_image_step_ocr_election_card_back_icon)
                    binding.backMaskLayout.visibility = View.GONE
                    binding.textFront.text = getString(R.string.gombe_credit_process_step_ocr_click_upload)
                    binding.textBack.text = getString(R.string.gombe_credit_process_step_ocr_click_upload)
                }
                else -> {
                    binding.ocrDataSecurityLayout.visibility = View.GONE
                    binding.ocrUploadCreditLimitAddTipsLayout.visibility = View.VISIBLE
                    binding.textShowOcrType.visibility = View.GONE
                    binding.ocrImageLayout.visibility = View.GONE
                }
            }
        }
    }

    /**
     * 设置数据安全提示
     */
    private fun showGombeCreditOcrDataSecurityTextView(){
        val typeTitle = selectTypeItem?.optString("title")
        val showKey = getString(R.string.gombe_credit_process_step_ocr_data_security_key)
        val showText = String.format(getString(R.string.gombe_credit_process_step_ocr_data_security),typeTitle,showKey)
        val startIndex = showText.indexOf(showKey)
        val spannable = SpannableString(showText)
        spannable.setSpan(ForegroundColorSpan(getColor(R.color.gombe_credit_FF000FCC)), startIndex, startIndex + showKey.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        _binding?.textOcrDataSecurity?.text = spannable
    }

    /**
     * 相机、相册
     */
    private fun showGombeCreditOcrPhotoDialog(eventRemark: String){
        if (photoDialog == null){
            photoDialog = DialogGombeCreditPhoto(requireContext(),object : DialogGombeCreditPhoto.IDialogCallback{
                override fun openCamera() {
                    addEventPointRequestAction(GombeCreditEventPointType.GOMBECREDIT_TRACK_CLICK.CAMERA,eventRemark)
                    if (EasyPermissions.hasPermissions(requireContext(), Manifest.permission.CAMERA)){
                        openGombeCreditStepOcrCamera()
                    } else {
                        showGombeCreditOcrPermissionReasonDialog()
                    }
                }
                override fun openAlbum() {
                    addEventPointRequestAction(GombeCreditEventPointType.GOMBECREDIT_TRACK_CLICK.ALBUM,eventRemark)
                    openGombeCreditStepOcrAlbum()
                }
            })
            photoDialog?.setCancelable(true)
            photoDialog?.setCanceledOnTouchOutside(true)
        }
        photoDialog?.setEventRemark(eventRemark)
        photoDialog?.show()
    }


    /**
     * 显示权限描述文案
     */
    private fun showGombeCreditOcrPermissionReasonDialog(){
        val item = GombeCreditPermissionHelper.queryGombeCreditPermissionItem4()
        val requestPermission = item.optString("permission")
        val dialog = DialogGombeCreditPermissionReason(requireContext(),requestPermission,object : DialogGombeCreditPermissionReason.IDialogCallback{
            override fun onClick(view: View?) {
                when(view?.id){
                    R.id.btnAgree -> {
                        addEventPointRequestAction(GombeCreditEventPointType.GOMBECREDIT_TRACK_CLICK.PERMISSION_REASON_DIALOG_AGREE,requestPermission)
                        EasyPermissions.requestPermissions(this@FragmentGombeCreditStepOcr, getString(R.string.gombe_credit_process_step_ocr_camera_reason),1001,Manifest.permission.CAMERA)
                    }
                    R.id.btnDeny -> {
                        addEventPointRequestAction(GombeCreditEventPointType.GOMBECREDIT_TRACK_CLICK.PERMISSION_REASON_DIALOG_DENY,requestPermission)
                    }
                }
            }
        })
        dialog.setCancelable(true)
        dialog.setCanceledOnTouchOutside(true)
        dialog.show()
        dialog.showGombeCreditPermissionReasonData(item)
    }

    /**
     * Ocr拍照
     */
    private val takePhotoResultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result: ActivityResult ->
        when (result.resultCode) {
            Activity.RESULT_OK -> {
                GombeCreditLogger.e(">>>>>>onActivityResult: data = " + result.data)
                result.data?.let {
                    val imgLocalPath = it.getStringExtra("imgLocalPath").toString()
                    val imgUrl = it.getStringExtra("imgUrl").toString()
                    showGombeCreditOCRUploadImageSuccess(imgLocalPath,imgUrl)
                }
            }
        }
    }

    /**
     * 打开相册
     */
    private fun openGombeCreditStepOcrAlbum(){
        pickMedia.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly))
    }

    /**
     * 打开相机
     */
    private fun openGombeCreditStepOcrCamera(){
        takePhotoResultLauncher.launch(Intent(context, ActGombeCreditCameraOcr::class.java))
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        // 进一步使用 EasyPermissions 处理后续结果
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    /**
     * 用户点击同意授权后会回调该方法
     */
    override fun onPermissionsGranted(requestCode: Int, perms: MutableList<String>) {
        perms.forEach {
            addEventPointRequestAction(GombeCreditEventPointType.GOMBECREDIT_TRACK_CLICK.PERMISSION_SYSTEM_AGREE, it)
        }
        if (requestCode == 1001){
            openGombeCreditStepOcrCamera()
        }
    }

    /**
     * 用户点击拒绝授权后会回调该方法
     */
    override fun onPermissionsDenied(requestCode: Int, perms: MutableList<String>) {
        perms.forEach {
            addEventPointRequestAction(GombeCreditEventPointType.GOMBECREDIT_TRACK_CLICK.PERMISSION_SYSTEM_DENY, it)
        }
        // 如果申请的权限中有任何一个权限存在 永久拒绝 的情况
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            // 设置 引导用户前往设置界面 自行设置权限的引导对话框
            AppSettingsDialog.Builder(this)
//                .setTitle("需要手动设置权限")
//                .setRationale("存在永久拒绝的权限 , 需要手动前往设置界面为应用进行授权")
//                .setPositiveButton("前往设置界面")
//                .setNegativeButton("不使用该功能")
                .build().show()
        }
    }

    override fun onRationaleAccepted(requestCode: Int) {
        GombeCreditLogger.e("onRationaleAccepted, code: $requestCode")
    }

    override fun onRationaleDenied(requestCode: Int) {
        GombeCreditLogger.e("onRationaleDenied, code: $requestCode")
    }

    @Deprecated("Deprecated in Java")
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (requestCode == 1001){
            // 判断五种权限是否申请成功
            val hasPermissions = EasyPermissions.hasPermissions(requireContext(), Manifest.permission.CAMERA)
            if (hasPermissions){
                openGombeCreditStepOcrCamera()
            }
        }
    }
    /**
     * 图片上传成功
     */
    fun showGombeCreditOCRUploadImageSuccess(imgPath: String, imgUrl: String) {
        if (selectTypeItem == null){
            return
        }
        _binding?.let { binding ->
            when(isFront){
                true -> {
                    imgFrontUrl = imgUrl
                    GombeCreditImageLoader.instance?.loadImageUrl(requireContext(),binding.imageFront,imgPath)
                    binding.frontMaskLayout.visibility = View.VISIBLE
                    binding.textFront.text = getString(R.string.gombe_credit_process_step_ocr_re_upload)
                    GombeCreditImageLoader.instance?.loadImageUrl(requireContext(),binding.imagePassportFront,imgPath)
                    binding.passportMaskLayout.visibility = View.VISIBLE
                    binding.textPassportFront.text = getString(R.string.gombe_credit_process_step_ocr_re_upload)
                    val eventRemark = "${selectTypeItem?.optString("ocrType")} Front $$$imgUrl"
                    addEventPointRequestAction(GombeCreditEventPointType.GOMBECREDIT_TRACK_FORM.STEP_OCR_UPLOAD_URL,eventRemark)
                }
                else -> {
                    imgBackUrl = imgUrl
                    GombeCreditImageLoader.instance?.loadImageUrl(requireContext(),binding.imageBack,imgPath)
                    binding.backMaskLayout.visibility = View.VISIBLE
                    binding.textBack.text = getString(R.string.gombe_credit_process_step_ocr_re_upload)
                    val eventRemark = "${selectTypeItem?.optString("ocrType")} Back $$$imgUrl"
                    addEventPointRequestAction(GombeCreditEventPointType.GOMBECREDIT_TRACK_FORM.STEP_OCR_UPLOAD_URL,eventRemark)
                }
            }
        }
    }

    /**
     * 提交Ocr数据
     */
    private fun onGombeCreditStepOcrSubmitAction(){
        if (selectTypeItem == null){
            return
        }
        var ocrType = ""
        selectTypeItem?.let {
            ocrType = it.optString("ocrType")
        }
        if (!isGombeCreditOcrAllowSubmit()){
            showErrorTipsDialog(getString(R.string.gombe_credit_dialog_tips_submit_error),ocrType)
            return
        }
        //如果是选举卡类型，需要按照身份证类型上传
        if (ocrType == "ELECTIONCARD"){
            ocrType = "IDCARD"
        }
        val params = JSONObject().addCommonParams().apply {
            put("path", GombeCreditApiPath.GOMBECREDIT_PATH.GOMBECREDIT_API_OCR_INFO_PATH)
            put("cardType",ocrType)//证件类型（PASSPORT、IDCARD、DRIVING、FACE、NONE）
        }
        if (imgFrontUrl.isNotEmpty()){
            params.put("cardImgUrl",imgFrontUrl)//证件图片正面
        }
        if (imgBackUrl.isNotEmpty()){
            params.put("cardBackImgUrl",imgBackUrl)//证件图片反面
        }
        addEventPointRequestAction(String.format(GombeCreditEventPointType.GOMBECREDIT_TRACK_CLICK.STEP_OCR_XX_NEXT,ocrType),"")
        // TODO: 进件信息点下一步 需上报所有埋点
        GombeCreditPointManager.getInstance().manualReport()

        submitGombeCreditOCRDataAction(params)
    }

    /**
     * 检查是否填写完整
     * 当且仅当 isMust=”NO“为非必填
     */
    private fun isGombeCreditOcrAllowSubmit(): Boolean{
        //没有选择类型
        if (selectTypeItem == null){
            return false
        }
        val ocrType = selectTypeItem?.optString("ocrType")
        if (ocrType == "NONE"){
            return true
        }
        if (imgFrontUrl.isEmpty()){
            return false
        }
        if (imgBackUrl.isEmpty() && (ocrType == "IDCARD" || ocrType == "DRIVING" || ocrType == "ELECTIONCARD")){
            return false
        }
        return true
    }

    /**
     * 图片上传
     */
    private fun uploadGombeCreditOCRImageAction(imgPath: String){
        showGombeCreditLoading(isTOuchOut = false, isCancel = false)
        HttpHelper.setTag(this)
        HttpHelper.upload(imgPath,object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                val obj = data.optJSONObject("obj")
                obj?.let {
                    val imgUrl = it.optString("url")
                    showGombeCreditOCRUploadImageSuccess(imgPath,imgUrl)
                }
            }
            override fun onRequestError(error: JSONObject) {
                showGombeCreditToast(error.optString("errorMsg"))
            }

            override fun onRequestFinish() {
                hideGombeCreditLoading()
            }
        })
    }

    /**
     * 提交
     */
    private fun submitGombeCreditOCRDataAction(params: JSONObject){
        val act = getAct() as ActGombeCreditProcessSteps
        act.onGombeCreditProcessStepSubmitAction(params)
    }

    override fun onGombeCreditPublishEvent(event: GombeCreditEventData) {
        super.onGombeCreditPublishEvent(event)
        when(event.eventType){
            GombeCreditEventData.TYPE.GOMBECREDIT_PROCESS_STEP_SUBMIT -> {
                onGombeCreditStepOcrSubmitAction()
            }
            else -> {

            }
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

    override fun onDestroy() {
        super.onDestroy()
        HttpHelper.cancelTag(this)
        addEventPointRequestAction(String.format(GombeCreditEventPointType.GOMBECREDIT_TRACK_PAGE.STEP_OCR_XX_END,eventRemark))
    }
}